import logging
from utils.neo4j_provider import neo4j


class AnswerSearcher:
    def __init__(self):
        self.num_limit = 20

    def search_main(self, sqls):
        """执行cypher查询，并返回相应结果"""
        final_answers = []
        for sql_ in sqls:
            question_type = sql_['question_type']  # 'question_type': 'symptom_disease'
            queries = sql_['sql']  # 'sql': ["MATCH (m:Disease)-[r:has_symptom]->(n:Symptom) where n.name = '看东西有时候清楚有时候不清楚' return m.name, r.name, n.name"]
            answers = []
            for cql in queries:
                ress = neo4j.execute_query(cql)  # logging.info("%s, %s", record["p"]["name"], record["p"]["generation"])
                answers += ress
            final_answer = self.answer_prettify(question_type, answers)
            if final_answer:
                final_answers.append(final_answer)
        return final_answers

    ###
    def answer_prettify(self, question_type, answers):
        """根据对应的qustion_type，调用相应的回复模板"""
        final_answer = []
        if not answers:
            return ''
        if question_type == 'disease_symptom':
            desc = [i['n.name'] for i in answers]
            subject = answers[0]['m.name']
            final_answer = '{0}的症状包括：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        if question_type == 'symptom_disease':
            desc = [i['m.name'] for i in answers]
            subject = answers[0]['n.name']
            final_answer = '可能是：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'disease_cause':
            desc = [i['m.cause'] for i in answers]
            subject = answers[0]['m.name']
            final_answer = '{0}可能的成因有：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'disease_prevent':
            desc = [i['m.prevent'] for i in answers]
            subject = answers[0]['m.name']
            final_answer = '{0}的预防措施包括：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'disease_lasttime':
            desc = [i['m.cure_lasttime'] for i in answers]
            subject = answers[0]['m.name']
            final_answer = '{0}治疗可能持续的周期为：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'disease_cureway':
            desc = [';'.join(i['m.cure_way']) for i in answers]
            subject = answers[0]['m.name']
            final_answer = '{0}可以尝试如下治疗：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'disease_cureprob':
            desc = [i['m.cured_prob'] for i in answers]
            subject = answers[0]['m.name']
            final_answer = '{0}治愈的概率为（仅供参考）：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'disease_easyget':
            desc = [i['m.easy_get'] for i in answers]
            subject = answers[0]['m.name']

            final_answer = '{0}的易感人群包括：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'disease_desc':
            desc = [i['m.desc'] for i in answers]
            subject = answers[0]['m.name']
            final_answer = '{0},熟悉一下：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'disease_acompany':
            desc1 = [i['n.name'] for i in answers]
            desc2 = [i['m.name'] for i in answers]
            subject = answers[0]['m.name']
            desc = [i for i in desc1 + desc2 if i != subject]
            final_answer = '{0}的症状包括：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        if question_type == 'disease_not_food':
            desc = [i['n.name'] for i in answers]
            subject = answers[0]['m.name']
            final_answer = '{0}，下列食物不要吃：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'disease_do_food':
            do_desc = [i['n.name'] for i in answers if i['r.name'] == '宜吃']
            recommand_desc = [i['n.name'] for i in answers if i['r.name'] == '推荐食谱']
            subject = answers[0]['m.name']
            final_answer = '{0}宜食的食物包括有：{1}\n推荐食谱包括有：{2}'.format(subject, ';'.join(list(set(do_desc))[:self.num_limit]),
                                                                 ';'.join(list(set(recommand_desc))[:self.num_limit]))

        elif question_type == 'food_not_disease':
            desc = [i['m.name'] for i in answers]
            subject = answers[0]['n.name']
            final_answer = '患有{0}的人最好不要吃{1}'.format('；'.join(list(set(desc))[:self.num_limit]), subject)

        elif question_type == 'food_do_disease':
            desc = [i['m.name'] for i in answers]
            subject = answers[0]['n.name']
            final_answer = '患有{0}的人建议多试试{1}'.format('；'.join(list(set(desc))[:self.num_limit]), subject)

        if question_type == 'disease_drug':
            desc = []
            for i in answers:
                desc.append(i['n.name'] + "(" + i['n.generic_name'] + ")" + "\n 【用法用量】：" + i['n.usage_dosage'] + "\n 【禁忌】：" + i['n.contraindications'])
            subject = answers[0]['m.name']
            final_answer = '{0}一般可以用：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'drug_disease':
            desc = [i['m.name'] for i in answers]
            subject = answers[0]['n.name']
            final_answer = '{0}主治的疾病有{1},可以试试'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'disease_check':
            desc = [i['n.name'] for i in answers]
            subject = answers[0]['m.name']
            final_answer = '{0}通常可以通过以下方式检查出来：{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        elif question_type == 'check_disease':
            desc = [i['m.name'] for i in answers]
            subject = answers[0]['n.name']
            final_answer = '通常可以通过{0}检查出来的疾病有{1}'.format(subject, '；'.join(list(set(desc))[:self.num_limit]))

        return final_answer


if __name__ == '__main__':
    searcher = AnswerSearcher()
    # 根据 症状描述 查出 对应的疾病
    sqls = [{'question_type': 'symptom_disease',
             'sql': ["MATCH (m:Disease)-[r:has_symptom]->(n:Symptom) where n.name = '看东西有时候清楚有时候不清楚' return m.name, r.name, n.name"]}]
    answer = searcher.search_main(sqls)
    print(answer)

    # 根据 疾病 查出 常用药品
    sqls = [{'question_type': 'disease_drug', 'sql': [
        "MATCH (m:Disease)-[r:used_drugs]->(n:Drug) where m.name = '干眼' return m.name, r.name, n.name,n.usage_dosage,n.generic_name,n.contraindications"]}]
    answer = searcher.search_main(sqls)
    print(answer)

    # 根据 药品 查出 给出饮食建议
    sqls = [{'question_type': 'disease_not_food', 'sql': ["MATCH (m:Disease)-[r:noteat_foods]->(n:Foods) where m.name = '干眼' return m.name, r.name, n.name"]}]
    answer = searcher.search_main(sqls)
    print(answer)
